package com.central.apps.service.impl;

import com.central.app.service.HandlerService;
import com.central.apps.entity.CostAttribute;
import com.central.apps.service.BudgetService;
import com.central.apps.service.CostOccupyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 成本占用接口实现类
 *
 * @author 李大超
 * @date 2023/2/17
 */
@Slf4j
@Service
public class CostOccupyServiceImpl implements CostOccupyService {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private BudgetService budgetService;

    /**
     * 成本占用或释放
     *
     * @param costAttribute
     * @param flag
     */
    @Override
    public void costOccupyRelease(CostAttribute costAttribute, boolean flag) throws Exception {
        Integer proId = costAttribute.getProId();
        Integer costItemId = costAttribute.getCostItemId();
        BigDecimal occupyCost = costAttribute.getOccupyCost();

        if (proId == null || costItemId == null || costItemId == 0 || occupyCost == null) {
            return;
        }

        // 更新年度预算预算项占用/释放相关信息
        budgetService.budgetOccupyRelease(proId, costItemId, occupyCost, flag);
    }

    /**
     * 成本判断
     *
     * @param costAttribute
     */
    @Override
    public String judgeCostEnough(CostAttribute costAttribute) throws Exception {
        Integer proId = costAttribute.getProId();
        Integer costItemId = costAttribute.getCostItemId();
        BigDecimal occupyCost = costAttribute.getOccupyCost();
        StringBuilder sb = new StringBuilder();
        if (proId == null || costItemId == null || costItemId == 0 || occupyCost == null) {
            return sb.toString();
        }

        // 查询成本是否够用
        Map<String, Object> map = handlerService.findOneBySql("select usefulamt from gq_probudget where proid = " + proId + " and id = " + costItemId);

        if (map != null && !map.isEmpty()) {
            String usefulamt = MapUtils.getString(map, "usefulamt");
            BigDecimal usefulamtDec = new BigDecimal(usefulamt);

            if (occupyCost.compareTo(usefulamtDec) > 0) {
                sb.append("项目对应可用预算不足(可用预算：").append(usefulamtDec).append(")，请联系项目负责人或者重新提起可用预算范围内的申请！");
            }
        }

        return sb.toString();
    }
}
